package com.astrob.activitys;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ProgressBar;

import com.alibaba.sdk.android.feedback.impl.FeedbackAPI;
import com.astrob.naviframe.Start;
import com.astrob.nhcmap.R;
import com.astrob.util.SysUtils;
import com.nhc.activity_fragment.MainTabActivity;
import com.nhc.database.manager.DBDataCenter;
import com.nhc.model.CoordParmFileHandle;
import com.nhc.model.LambertParmFileHandle;
import com.nhc.model.MapSetInfo;
import com.nhc.model.NaviTrackSetInfo;
import com.nhc.model.PaomaoInfo;
import com.nhc.model.PoiCollectInfo;
import com.nhc.model.SensorSetInfo;
import com.nhc.model.TransParaSevenFileHandle;
import com.nhc.model.TripDataFileHandle;
import com.nhc.model.TripDatainfo;
import com.nhc.model.TwoPointsFileHandle;

import java.io.File;

import zuo.biao.library.util.Log;

public class WelcomeActivity extends Activity {

    private ProgressBar progress;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        DisplayMetrics metrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(metrics);
        float widthDp = metrics.widthPixels / metrics.density;
        if (metrics.widthPixels <= 240) {
            SysUtils.getInstance().is240x320 = true;//< 16dp || == 22的中文字不能显示
        }

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.welcome);

        progress = (ProgressBar) this.findViewById(R.id.progress);

        permissonHandle();
    }

    private void permissonHandle() {
        //安卓6.0权限请求
        if (ContextCompat.checkSelfPermission(WelcomeActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(WelcomeActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(WelcomeActivity.this, new String[]{android.Manifest.permission.WRITE_EXTERNAL_STORAGE}, 111);
        } else {
            AppContext.getInstances().setDatabase();    //初始化数据库
            startNavi();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean writeAccepted = false;
        switch (requestCode) {
            case 111:
                writeAccepted = grantResults[0] == PackageManager.PERMISSION_GRANTED;
                if (writeAccepted) {
                    AppContext.getInstances().setDatabase();    //初始化数据库
                    startNavi();
                } else {
                    moveTaskToBack(false);//应用退到后台
                    System.exit(0);
                }
                break;
        }
    }

    private void startMap() {
        progress.setVisibility(View.INVISIBLE);

        Intent intent0 = getIntent();
        String action = intent0.getAction();
        String strT = "";
        if (intent0.ACTION_VIEW.equals(action)) {
            Uri uri = intent0.getData();
            strT = Uri.decode(uri.getEncodedPath());
        }

//		Intent intent = new Intent(WelcomeActivity.this, NaviActivity.class);
        startActivity(MainTabActivity.createIntent(WelcomeActivity.this, strT));
        WelcomeActivity.this.finish();

    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    startMap();
                    break;
            }
        }
    };

    private void startNavi() {
        Log.e("BHCnav","Test  6");
        
        progress.setVisibility(View.VISIBLE);
        new Thread() {
            @Override
            public void run() {
                try {
                    if (SysUtils.getInstance().is240x320) {
                        Thread.sleep(3000);//可能是开机启动时外置sd卡没有加载
                    } else {
                        Thread.sleep(500);
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                AppContext.getInstances().init();

                if (Start.getInstance().initialize(WelcomeActivity.this)) {
                    TripDatainfo.DATATYPE_NAMES = getResources().getStringArray(R.array.tripdatainfo_datatype_names);
                    DBDataCenter.getInstance().init();
                    TripDataFileHandle.getInstance();
                    TransParaSevenFileHandle.getInstance();
                    DBDataCenter.getInstance().clearTrippt();//当前时间准确后删除3天前的行程
                    CoordParmFileHandle.getInstance().load(WelcomeActivity.this);
                    MapSetInfo.getInstance().load(WelcomeActivity.this);
                    PaomaoInfo.getInstance().load(WelcomeActivity.this);
                    PoiCollectInfo.getInstance().load(WelcomeActivity.this);
                    NaviTrackSetInfo.getInstance().load(WelcomeActivity.this);
                    TwoPointsFileHandle.getInstance().load(WelcomeActivity.this);
                    LambertParmFileHandle.getInstance().load(WelcomeActivity.this);
                    SensorSetInfo.getInstance().load(WelcomeActivity.this);


                    File file1 = new File(Start.RUNDIR + "/HCMap_EX/GPX/");
                    if (!file1.exists()) {
                        file1.mkdirs();
                    }
                    File file2 = new File(Start.RUNDIR + "/HCMap_EX/KML/");
                    if (!file2.exists()) {
                        file2.mkdirs();
                    }
                    File file3 = new File(Start.RUNDIR + "/HCMap_EX/image/");
                    if (!file3.exists()) {
                        file3.mkdirs();
                    }
                    File file4 = new File(Start.RUNDIR + "/HCMap_EX/SHP/");
                    if (!file4.exists()) {
                        file4.mkdirs();
                    }

                    Message msg = new Message();
                    msg.what = 1;
                    handler.sendMessage(msg);
                } else {
                    WelcomeActivity.this.finish();
                    System.exit(0);
                    return;
                }
            }
        }.start();
    }

}